﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace GoodStuff.Net
{
    /// <summary>
    /// http://stackoverflow.com/questions/186800/is-it-possible-to-specify-proxy-credentials-in-your-web-config
    /// </summary>
    public class AuthenticatingProxy : IWebProxy
    {
        AuthenticatingProxyConfiguration configuration;

        public AuthenticatingProxy()
        {
            //load configuration.
            configuration = ConfigurationHelper.GetSection<AuthenticatingProxyConfiguration>("goodStuff/authenticatingProxy");
        }

        public ICredentials Credentials
        {
            get
            {
                return new NetworkCredential(configuration.UserName, configuration.Password, configuration.Domain);
            }
            set
            {               
            }
        }

        public Uri GetProxy(Uri destination)
        {
            return new Uri(configuration.ProxyUrl);
        }

        public bool IsBypassed(Uri host)
        {
            var config = ConfigurationHelper.GetSection<System.Net.Configuration.DefaultProxySection>("system.net/defaultProxy");

            if (config != null && config.BypassList != null)
            {
                foreach (System.Net.Configuration.BypassElement element in config.BypassList)
                {
                    if (System.Text.RegularExpressions.Regex.IsMatch(host.ToString(), element.Address, System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
    }
}
